#include "main.h"
typedef struct delete delete;
int ListInitiate(LNode** head) {
    *head = (LNode*)malloc(sizeof(LNode));
    if (!*head) {
        return 1;
    }
    (*head)->next = NULL;
    return 0;
}

int ListLength(LNode* head) /* 单链表的长度*/ {
    LNode* p;
    p = head->next;/*指向头结点的下一个节点，计算单链表的长度*/
    int i = 0;
    while (p) {
        i++;
        p = p->next;
    }
    return i;
}

int ListInsert(LNode* head, int i, DataType x) {
    LNode* p = head, * s;
    int j = -1;
    while (p && j < i - 1) { p = p->next; ++j; }
    if (!p || j > i) return 1;
    s = (LNode*)malloc(sizeof(LNode));
    s->data = x;

    s->next = p->next;
    p->next = s;

    return 0;
}

int ListDelete(LNode* head, int i, DataType* x) {
    LNode* p = head; int j = -1;
    while (p->next && j < i - 1) //p->next???
    {
        p = p->next; ++j;
    }
    if (!(p->next) || j > i - 1) //防止i>n或指向指针超过所给位置
        return 1;//若是error须定义标识符
    LNode* q = p->next;
    p->next = q->next;
    *x = q->data;
    free(q);//deleate
    return 0;
}

int ListGet(LNode* head, int i, DataType* x) {
    LNode* p;
    p = head->next; int j = 0;
    while (p && j < i) {
        p = p->next;
        ++j;
    }
    if (!p || j > i) return 1;
    *x = p->data;
    return 0;
}

int Destroy(LNode** head)
{
    LNode* p, * r;
    p = *head;
    while (p != NULL)
    {
        r = p;
        p = p->next;
        free(r);
    }
    *head = NULL;
    return 0;
}

void main(void) {
    LNode* head;
    int i, x;
    ListInitiate(&head);
    for (i = 0; i < 10; i++) {
        if (ListInsert(head, i, i + 1) == 1) 
        {
            printf("错误! \n");
            return;
        }
    }

    if (ListDelete(head, 4, &x) == 1) { 
        printf("错误! \n");
        return;
    }
    printf("%d\n", ListLength(head));

    for (i = 0; i < ListLength(head); i++) {
        if (ListGet(head, i, &x) == 1) 
        {
            printf("错误! \n");
            return;
        }
        else printf("%d", x);
    }

    Destroy(&head);
}
